package com.lz.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import java.time.LocalDate;
import java.util.Map;

/**
 * MyServletContextListener.. 实现ServletContextListener
 *
 * @author Lizhong
 * @date 2019/4/12
 */
// @WebListener
public class MyServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("MyServletContextListener context 初始化");
        ServletContext servletContext = servletContextEvent.getServletContext();
        // 动态注册 servlet
        ServletRegistration.Dynamic myServlet = servletContext.addServlet("myServlet", MyServlet.class);
        myServlet.addMapping("/myServlet");

        // 打印所有 servlet
        Map<String, ? extends ServletRegistration> map = servletContext.getServletRegistrations();
        map.values().stream().map(ServletRegistration::getName).forEach(System.out::println);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // 停止tomcat会调用该方法
        System.out.println(LocalDate.now() +"\t MyServletContextListener 结束了");
    }
}
